<template>
    <div class="control-setting-container_item-setting">
        <el-form label-position="top" label-width="80px" :model="item" :disabled="_isReadOnly">
            <el-form-item label="标题">
                <el-autocomplete
                    v-model="item.name"
                    :fetch-suggestions="predictionSearch"
                    placeholder="请输入内容"
                    @focus="_focus"
                    @blur="_blur"
                    @select="handleSelect"
                ></el-autocomplete>
            </el-form-item>
            <div class="online">
                <el-form-item label="类型">
                    <el-select v-model="item.valueKindId" @change="changeValueKind">
                        <el-option v-for="(item, index) in typeList" :value="item.id" :label="item.label" :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="必填" class="required-item">
                    <el-switch
                        v-model="item.required"
                        active-color="#32A78F"
                        inactive-color="#CACDCE">
                    </el-switch>
                </el-form-item>
            </div>
            <el-form-item label="单位">
                <el-select v-model="item.unitKindId" class="unit-select" clearable @change="changeUnit">
                    <el-option
                        v-for="item in unitsData"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <div class="line"></div>
            <template v-if="['6', '7'].includes(item.valueKindId)">
                <el-button type="text" class="options-btn" @click="editOptions" style="margin-bottom: 10px;">批量设置选项</el-button>
                <div class="item-option-result">
                    <template v-for="(it, index) in item.options.slice(0, 5)">
                        <div class="item" :key="index">
                            <el-input v-model="it.name" @focus="setOld(it.name)" @blur="checkName(it.name, index)"></el-input>
                            <span class="delete-icon" @click="deleteOption(index)">
                                <icon-svg name="icon-control-delete"></icon-svg>
                            </span>
                        </div>
                    </template>
                </div>
            </template>
            <el-form-item label="填写格式" v-if="['3', '11'].includes(item.valueKindId)">
                <el-select v-model="item.fillType" @change="changeFillType">
                    <el-option label="年-月-日" value="date"></el-option>
                    <el-option label="年-月-日 时:分:秒" value="dateTime"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="提示语" v-if="['1', '2', '12', '13'].includes(item.valueKindId)">
                <el-input v-model="item.placeholder"></el-input>
            </el-form-item>
            <el-form-item label="填写长度" v-if="['12'].includes(item.valueKindId)" class="value-length-input">
                <span class="tips">数字填写的位数，最大30</span>
                <el-input v-model="item.valueLength" @input="checkValueLength" placeholder="不限制长度"></el-input>
            </el-form-item>
            <el-form-item label="显示条件" v-if="item.valueKindId === '6' && !isTableItem && !item.cascadeId" class="set-show-box">
                <p class="tips">设置显示条件后，[选项]批量编辑此处设置将会失效</p>
                <display-condition :itemControl.sync="item" :list.sync="currentList"></display-condition>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts">
import { Component, Prop, PropSync, Vue, Watch } from "vue-property-decorator";
import { dialogForm } from "../../components/update-options/index";
import { getRandomId } from "@/utils";
import DisplayCondition from "../display-condition/index.vue";

@Component({
    components: {
        DisplayCondition
    }
})
export default class ItemSetting extends Vue {
    @Prop({ type: Array, default: [] }) readonly unitsData!: any[];
    @PropSync("itemData", { type: Object, default: () => { return {}; } }) private item!: any;
    @PropSync(
        'list',
        {
            type: Array,
            default: () => {
                return [];
            }
        })
    readonly currentList!: any[];

    @Watch("item", { immediate: true, deep: true })
    changeItem() {
        // 在表格中的表单项列表
        let list: any[] = [];
        this.currentList.forEach((item: any) => {
            if (item.itemType === 0) {
                item.items.forEach((it: any) => {
                    if (it.itemType === 1) {
                        list = list.concat([], it.items);
                    }
                });
            } else if (item.itemType === 1) {
                list = list.concat([], item.items);
            }
        });
        const index = list.findIndex((item: any) => item.tempId === this.item.tempId);
        this.isTableItem = index !== -1;

        if (['3', '11'].includes(this.item.valueKindId)) {
            this.item.fillType = this.item.valueKindId === "3" ? "date" : "dateTime";
        }
        if (['12'].includes(this.item.valueKindId)) {
            this.item.valueLength = this.item.valueLength === "" ? "" : Number(this.item.valueLength);
        }
    }

    @Watch("currentList", { immediate: true, deep: true })
    changeList() {
        this.changeItem();
    }

    optionsString = ""
    typeList = [
        { id: "1", value: "input-text", label: "单行文本" },
        { id: "2", value: "input-textarea", label: "多行文本" },
        { id: "3", value: "input-date", label: "日期选择" },
        { id: "11", value: "input-datetime", label: "日期时间选择" },
        { id: "4", value: "location", label: "定位" },
        { id: "6", value: "select", label: "单选" },
        { id: "7", value: "cascader", label: "多选" },
        { id: "12", value: "input-num", label: "整数" },
        { id: "13", value: "input-num-decimal", label: "小数" },
        { id: "5", value: "upload-img", label: "上传图片" },
        { id: "8", value: "upload-video", label: "上传视频" },
        { id: "9", value: "upload-record", label: "上传录音" },
        { id: "10", value: "upload-file", label: "上传文件" }
    ];

    isTableItem = true

    get _isReadOnly() {
        return this.$route.query.isDetail === '1' || this.$route.query.isSend === 'send';
    }

    oldName = ""
    oldNameInput = ""


    _focus() {
        this.oldNameInput = this.item.name;
    }

    _blur() {
        if (!this.item.name) {
            this.item.name = this.oldNameInput;
        }
        this.oldNameInput = "";
    }

    setOld(val: any) {
        this.oldName = val;
    }

    checkName(val: any, index: any) {
        if (!val) {
            this.item.options[index].name = this.oldName;
        }
    }

    checkValueLength() {
        this.item.valueLength = this.item.valueLength.replace(/^(0+)|[^\d]+/g, '');
        if (this.item.valueLength > 30) {
            this.item.valueLength = 30;
        } else if (this.item.valueLength <= 0) {
            this.item.valueLength = "";
        } else {
            this.item.valueLength = Number(this.item.valueLength);
        }
        this.$forceUpdate();
    }

    setOptionsString() {
        this.optionsString = this.item.options && this.item.options.length ? this.item.options.map((item: any) => item.name).join(",") : "添加选项";
    }

    // 修改时间格式
    changeFillType(val: any) {
        this.item.valueKindId = val === "date" ? "3" : "11";
    }

    editOptions() {
        if (this.$route.query.isDetail === "1" || this.$route.query.isSend === "send") return false;
        dialogForm({
            optionsList: JSON.parse(JSON.stringify(this.item.options || [])),
            sure: (vm: any, model: any) => {
                this.item.options = model;
                this.setOptionsString();
                vm.close();
            }
        });
    }

    deleteOption(index: any) {
        this.item.options.splice(index, 1);
    }

    // 表单项默认配置
    changeValueKind(val: any) {
        if (['3', '11'].includes(val)) {
            this.item.fillType = "date";
        } else {
            this.item.fillType = undefined;
        }
        if (['3', "6", "7", '11'].includes(val)) {
            this.item.placeholder = "请选择";
        } else if (['1', '2', '12'].includes(val)) {
            this.item.placeholder = "请输入";
        } else {
            this.item.placeholder = "";
        }
        if (val === "12") {
            this.item.valueLength = "";
        }
        if (!["6", "7"].includes(val)) {
            this.item.options = [];
        } else {
            if (!(this.item.options && this.item.options.length)) {
                this.item.options = [];
            }
        }
    }

    async predictionSearch(queryString: any, cb: any) {
        let data: any = [];
        if (queryString) {
            const res = await this.$server["label/prediction"]({
                loader: false,
                data: {
                    name: queryString
                }
            });
            if (res.data.code === 200) {
                data = res.data.data.map((item: any) => {
                    return {
                        value: item.name,
                        id: item.id
                    };
                });
            }
        }
        cb(data);
    }

    async handleSelect(item: any) {
        const res = await this.$server["resource/getRowData"]({
            data: {
                id: item.id
            }
        });
        if (res.data.code === 200) {
            const { name, valueKindId, options } = res.data.data;
            this.item.name = name;
            this.item.valueKindId = valueKindId;
            this.item.options = options ? options.map((cur: any) => {
                return {
                    ...cur,
                    tempId: cur.id || getRandomId()
                };
            }) : [];
            this.item.fillType = valueKindId === "3" ? "date" : undefined;
        }
    }

    changeUnit() {
        if (this.item.unitKindId) {
            this.$set(this.item, 'unitKindName', this.unitsData.filter((item: any) => item.id === this.item.unitKindId)[0].name);
        } else {
            this.item.unitKindName = null;
        }
    }
}
</script>

<style lang="scss" scoped>
.control-setting-container_item-setting {
    .line {
        height: 1px;
        background: #EDEFF2;
        margin-bottom: 16px;
    }
    .options-btn {
        font-size: 14px;
        font-family: "PingFang SC Medium";
        line-height: 20px;
        color: #2C82C9;
        padding: 0;
    }
    .item-option-result {
        .item {
            margin-bottom: 10px;
            @include flexLayout(flex,justify,center)
        }
        ::v-deep {
            .el-input {
                width: calc(100% - 28px);
            }
        }
        .delete-icon {
            cursor: pointer;
            font-size: 20px;
        }
    }
    .set-show-box {
        .tips {
            margin: 0;
            color: #C7CAD3;
        }
    }
    .value-length-input {
        .tips {
            position: absolute;
            left: 70px;
            top: -25px;
            color: #37383a;
            font-size: 12px;
            line-height: 1;
        }
    }
    .online {
        @include flexLayout(flex,normal,normal);
        & > * {
            width: 50%;
        }
        .required-item {
            padding-left: 20px;
        }
    }
    .unit-select {
        width: 202px;
    }
}
</style>
